<?php

namespace app\common\model\system;

use app\common\model\auth\AuthMenuModel;
use Detection\MobileDetect;
use GeoIp2\Database\Reader;
use app\common\model\BaseModel;
use app\common\model\auth\AuthAdminOperateLogModel;

class SystemAbnormalModel extends BaseModel
{
    protected $table = 't_system_abnormal';

    /**
     * 记录系统异常日志
     * @param object $exception
     */
    public function addException($exception): void
    {
        try {
            $ispDbReader = new Reader('./static/GeoLite2-City_20240611/GeoLite2-City.mmdb');
            $record = $ispDbReader->city(request()->ip());
            $address = '';
            if (isset($record->country->names['zh-CN'])) {
                $address .= $record->country->names['zh-CN'];
            }
            if (isset($record->mostSpecificSubdivision->names['zh-CN'])) {
                $address .= ' ' . $record->mostSpecificSubdivision->names['zh-CN'];
            }
            if (isset($record->city->names['zh-CN'])) {
                $address .= ' ' . $record->city->names['zh-CN'];
            }

            $latitude = $record->location->latitude;
            $longitude = $record->location->longitude;
        } catch (\Exception $e) {
        }

        try {
            $mobileDetect = new MobileDetect;
            if ($mobileDetect->isMobile()) {
                $device = '手机';
            } elseif ($mobileDetect->isTablet()) {
                $device = '平板';
            } else {
                $device = '电脑';
            }
        } catch (\Exception $e) {

        }

        $url = strtolower(ltrim(request()->baseUrl(), '/'));
        $menuInfo = (new AuthMenuModel)->where('url', $url)->find();
        $param = request()->param();
        unset($param['password'], $param['confirm_password']);

        $this->insert([
            'admin_id' => get_admin_info()['id'] ?? 0,
            'url' => $url,
            'menu_id' => $menuInfo['id'] ?? 0,
            'menu_name' => $menuInfo['name'] ?? 0,
            'menu_name_path' => (new AuthMenuModel)->getMenuNamePath($menuInfo['id'] ?? 0),
            'method' => request()->method(),
            'param' => json_encode($param, JSON_UNESCAPED_UNICODE),
            'ip' => request()->ip(),
            'address' => $address ?? '',
            'latitude' => $latitude ?? 0,
            'longitude' => $longitude ?? 0,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            'device' => $device,
            'abnormal' => json_encode([
                'error' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine()
            ], JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s'),
        ]);

        $operateLogId = get_operate_log_id();
        if ($operateLogId) {
            (new AuthAdminOperateLogModel)->where('id', $operateLogId)->update([
                'abnormal' => json_encode([
                    'error' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine()
                ], JSON_UNESCAPED_UNICODE)
            ]);
        }
    }

}